﻿using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SqlSugarDemo.Utils
{
    public class SqlSugarUtil
    {
        public static readonly string ConnectionString = "Data Source=localhost;Port=3306;User ID=root;Password=123456;Initial Catalog=sqlsugar_test;Charset=utf8mb4;SslMode=none;Allow User Variables=True;connection timeout=600;";

        #region CreateSqlSugarClient
        public static SqlSugarScope CreateSqlSugarClient()
        {
            SqlSugarScope db = new SqlSugarScope(new ConnectionConfig()
            {
                ConnectionString = ConnectionString,//连接符字串
                DbType = SqlSugar.DbType.MySql, //数据库类型
                IsAutoCloseConnection = true //不设成true要手动close
            });

            return db;
        }
        #endregion

        #region CreateModels 生成实体类
        /// <summary>
        /// 生成实体类
        /// </summary>
        public static void CreateModels(SqlSugarClient db, string tableName = null)
        {
            foreach (DbTableInfo dbTableInfo in db.DbMaintenance.GetTableInfoList())
            {
                //表名处理
                List<string> tableNameParts = dbTableInfo.Name.Split('_').ToList();
                tableNameParts = tableNameParts.ConvertAll<string>(item => item.Substring(0, 1).ToUpper() + item.Substring(1).ToLower());
                string entityName = string.Join(string.Empty, tableNameParts);
                db.MappingTables.Add(entityName, dbTableInfo.Name);

                //属性名处理
                foreach (DbColumnInfo dbColumnInfo in db.DbMaintenance.GetColumnInfosByTableName(dbTableInfo.Name))
                {
                    List<string> colunmNameParts = dbColumnInfo.DbColumnName.Split('_').ToList();
                    colunmNameParts = colunmNameParts.ConvertAll<string>(item => item.Substring(0, 1).ToUpper() + item.Substring(1).ToLower());
                    string fieldName = string.Join(string.Empty, colunmNameParts);
                    db.MappingColumns.Add(fieldName, dbColumnInfo.DbColumnName, entityName);
                }
            }
            if (tableName != null)
            {
                db.DbFirst.IsCreateAttribute().Where(tableName).CreateClassFile("d:\\_临时文件\\SqlSugar\\Models", "Models");
            }
            else
            {
                db.DbFirst.IsCreateAttribute().CreateClassFile("d:\\_临时文件\\SqlSugar\\Models", "Models");
            }
        }
        #endregion

    }
}
